import { useContext } from 'react';
import classNames from 'classnames';
import { history, useLocation } from 'umi';

import { MenuContext } from './Menu';

const MenuItem = (props) => {
  const {
    pathKey,
    disabled,
    className,
    style,
    children: titleRender,
    route,
    tagRender,
    MenuIndex,
    isBottom,
    onMenuClick,
    pathList,
  } = props;

  const context = useContext(MenuContext);
  const currentPathnameList = useLocation()
    .pathname.split('/')
    .filter((item) => !!item);

  // 判断高亮
  const isActive = () => {
    if ('/' + currentPathnameList?.[0] === route.path) return true;
    if (currentPathnameList === '') return;
    if (MenuIndex === 0)
      return '/' + (currentPathnameList?.[0] || '') === route.path;
    if (MenuIndex === 1) return route.path === currentPathnameList?.[1];
    if (MenuIndex === 2) return route.path === currentPathnameList?.[2];
    return route.path === currentPathnameList?.[3];
  };

  const classes = classNames('menu-item', className, {
    disabled: disabled,
    active: isActive(),
    bottom: isBottom,
    'sec-menu-item': MenuIndex === 1,
  });

  // 拼接路径，判断根路径
  const jointPath = (pList) => {
    let resPath;
    pList.forEach((path) => {
      if (path.startsWith('/')) {
        resPath = path;
      } else {
        resPath = `${resPath}/${path}`;
      }
    });
    return resPath;
  };

  // 点击Link跳转
  const handleClick = () => {
    // 自定义点击事件
    if (context.onSelect && !disabled && typeof pathKey === 'string') {
      context.onSelect(pathKey);
    }
    if (route.href) {
      window.open(route.href);
      return;
    }
    onMenuClick && onMenuClick();
    let resPath;
    // 零级导航自动定位到每项的第一个
    if (MenuIndex === 0) {
      if (!route.routes) {
        resPath = route.path;
      } else if (route.routes?.[0].routes?.length) {
        resPath = `${route.path}/${route.routes[0].path}/${route.routes[0].routes[0].path}`;
      } else {
        resPath = `${route.path}/${route.routes?.[0].path}`;
      }
    }
    history.push(resPath || jointPath(pathList));
  };

  return (
    !route.hideInMenu && (
      <li className={classes} style={style}>
        <a className="item-link" onClick={handleClick}>
          <span className="item-content-container">
            <span className="icon-container">{route.logo}</span>
            <span className="menu-item-text">{titleRender}</span>
            {tagRender}
          </span>
        </a>
      </li>
    )
  );
};

MenuItem.displayName = 'MenuItem';
export default MenuItem;
